<script setup>
import MwTable from "./component/MwTableCamera";
import SearchTable from "./component/SearchCamera"
import MwDialog from "@/components/Dialog"
import { ElMessage, ElMessageBox } from 'element-plus'

import { CirclePlus, VideoPlay, CloseBold, Plus, Minus } from '@element-plus/icons-vue'
import { ref, reactive, getCurrentInstance, onMounted, watch, toRaw } from "vue"
import { globalStore } from "@/store/global"
import moment from "moment";

const globalVue = globalStore();

const instance = getCurrentInstance()
const _this = instance.appContext.config.globalProperties //vue3获取当前this

// 生命周期
onMounted(async () => {
  getTableData();
  algorithmSelect.value = await globalVue.getSelect('algorithmSelect');
  ratioSelect.value = await globalVue.getSelect('ratioSelect');
  pixelSelect.value = await globalVue.getSelect('pixelSelect');
  locationSelect.value = await globalVue.getSelect('locationSelect');
  stateSelect.value = await globalVue.getSelect('stateSelect');
})

// --------------------- 下拉数据 --------------------
const algorithmSelect = ref([]);
const ratioSelect = ref([]);
const pixelSelect = ref([]);
const locationSelect = ref([]);
const stateSelect = ref([]);


// --------------------- 表格数据 --------------------
const tableData = ref([]);
const tableLoading = ref(false);
const tableRow = ref(null);
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});
const searchForm = reactive({});

function getTableData(){
  let params = {
    ...pagination,
    ...searchForm
  }
  tableLoading.value = true;
  instance.proxy.$http.get('statistics.getCameraList',{ params }).then(res=>{
    let {content, totalElements} = res.data;
    tableData.value = content;
    pagination.total = totalElements;
    tableLoading.value = false;
  }).catch(err => tableLoading.value = false)
}
function onRefresh(){
  Object.keys(searchForm).map(key => {
    delete searchForm[key];
  })
  getTableData();
}
function onEdit(row){
  tableRow.value = row;
  changeDialog(true, 'Edit');
};
function onDelete(row){
  ElMessageBox.confirm('Delete Camera ？', 'Delete', {
    confirmButtonText: 'Confirm',
    cancelButtonText: 'Cancel'
  }).then(() => {
    instance.proxy.$http.delete('statistics.deleteCamera', {data: {id: row.id + ''}}).then(res=>{
      getTableData();
      ElMessage({
        type: 'success',
        message: 'Delete Driver successfully',
      })
    })
  }).catch(() => {})
}

// --------------------- 弹框数据 --------------------

let dialogRefCamera = ref(null);
let dialogData = reactive({
  show: false,
  state: 'Add', //  Add Edit
  tabsActive: 0,
  tabsList: [
    {label: "Camera Information", value: 0},
    {label: "Algorithm Information", value: 1},
  ],
  cameraForm: {
    coordinate: {}
  }, // Camera
  trackForm: {
    type: 1,
    isAble: false,
    detection_min_size: '',
    detection_max_size: '',
    detectionPeriod: [],
    detectionArea: {},
  }, // Track
  faceForm: {
    type: 2,
    isAble: false,
    detectionPeriod: [],
    detectionArea: {},
  }, // Face
  riskForm: {
    type: 3,
    isAble: false,
    gender: '',
    age: '',
    hat: '',
    wearingGlasses: '',
    backpack: '',
    handbag: '',
    detectionPeriod: [],
    detectionArea: {},
  }, // Risk
  fallingForm: {
    type: 4,
    isAble: false,
    detectionPeriod: [],
    detectionArea: {},
  }, // Falling
  remnantForm: {
    type: 5,
    isAble: false,
    alert_time_threshold: '',
    alert_detection_interval: '',
    detectionPeriod: [],
    detectionArea: {},
  }, // Remnant
});
let collapseArr = ref(['1', '2', '3', '4', '5']);

function tabsClick(value){
  dialogData.tabsActive = value;
  if (value == 1 && dialogData.state == 'Edit') {
    getAlgorithmData()
  }
}
async function dialogSubmit(){
  if (!dialogRefCamera.value) return;
  await dialogRefCamera.value.validate((valid, fields) => {
    if (valid) {
      formatFormData();
      if (dialogData.state == 'Add') {
        instance.proxy.$http.post('statistics.insertCamera', dialogData.cameraForm).then(res=>{
          getTableData();
          changeDialog(false, null)
        })
      }else{
        instance.proxy.$http.put('statistics.updateCamera', dialogData.cameraForm).then(res=>{
          getTableData();
          changeDialog(false, null)
        })
      }
    } else {
      tabsClick(0);
      console.log('error submit!', fields)
    }
  })
}
function changeDialog(show, state) {
  dialogData.show = show;
  if (show) {
    tabsClick(0);
    if (state == 'Edit') {
      Object.assign(dialogData.cameraForm, tableRow.value);
      let coordinate = {};
      tableRow.value.coordinate.split(',').forEach((i, index) => coordinate['q' + (index + 1)] = i);
      dialogData.cameraForm.coordinate = coordinate || {};
    }
  } else {
    dialogRefCamera.value?.resetFields();
    function staticData(type){
      return {detectionPeriod: [], detectionArea: {}, type, isAble: false};
    }
    dialogData.cameraForm = {coordinate: {}};
    Object.keys(dialogData.trackForm).forEach(i => {
      dialogData.trackForm[i] = '';
      Object.assign(dialogData.trackForm, staticData(1))
    })
    Object.keys(dialogData.faceForm).forEach(i => {
      dialogData.faceForm[i] = '';
      Object.assign(dialogData.faceForm, staticData(2))
    })
    Object.keys(dialogData.riskForm).forEach(i => {
      dialogData.riskForm[i] = '';
      Object.assign(dialogData.riskForm, staticData(3))
    })
    Object.keys(dialogData.fallingForm).forEach(i => {
      dialogData.fallingForm[i] = '';
      Object.assign(dialogData.fallingForm, staticData(4))
    })
    Object.keys(dialogData.remnantForm).forEach(i => {
      dialogData.remnantForm[i] = '';
      Object.assign(dialogData.remnantForm, staticData(5))
    })
  }
  if(state) dialogData.state = state;
}
function collapseChange(value){
  collapseArr.value = value;
}
function collapseIncludes(value){
  return collapseArr.value.includes(value);
}
function getAlgorithmData(){
  instance.proxy.$http.get('statistics.getAlgorithmByCameraId', {params: {cameraId: tableRow.value.id}}).then(res=>{
    res.data.forEach(i => {
      let form = {
        detectionArea: {}
      };
      if (i.detectionArea) {
        let detectionArea = JSON.parse(i.detectionArea);
        detectionArea.polygons[0].data.forEach((j, ind) => (form.detectionArea['q' + (ind + 1)] = j));
      }
      if(i.detectionPeriod){
        form.detectionPeriod = i.detectionPeriod.split('-').map(x => moment('2023-01-01 ' + x + ':00'));
      }
      if (i.parameter) {
        i.parameter.split(',').forEach(y => {
          let keyValue = y.split(':');
          form[keyValue[0]] = keyValue[1];
        })
      }
      form['isAble'] = !!i.isAble;
      Object.assign(i, form);
      if(i.type == 1) dialogData.trackForm = i;
      if(i.type == 2) dialogData.faceForm = i;
      if(i.type == 3) dialogData.riskForm = i;
      if(i.type == 4) dialogData.fallingForm = i;
      if(i.type == 5) dialogData.remnantForm = i;
    })
  })
}

function formatDetectionArea(data, type = ''){
  let obj = {"polygons": [{"data": []}]}, params = {};
  Object.keys(data['detectionArea']).forEach(i => {
    obj.polygons[0].data.push(data['detectionArea'][i])
  })
  params['detectionArea'] = JSON.stringify(obj);
  let timeSlot = data.detectionPeriod.concat();
  params['detectionPeriod'] = timeSlot.map(i => moment(i).format('HH:mm')).join("-");
  if(type == 'track'){
    params['parameter'] = [`detection_min_size:${data?.detection_min_size}`, `detection_max_size:${data?.detection_max_size}`] + '';
  }
  if(type == 'risk'){
    params['parameter'] = [
      `wearing glasses:${data?.wearingGlasses}`, 
      `hat:${data?.hat}`,
      `age:${data?.age}`,
      `gender:${data?.gender}`,
      `backpack:${data?.backpack}`,
      `handbag:${data?.handbag}`,
    ] + '';
  }
  if(type == 'remnant'){
    params['parameter'] = [`alert_time_threshold:${data?.alert_time_threshold}`, `alert_detection_interval:${data?.alert_detection_interval}`] + '';
  }
  params.isAble = Number(data.isAble);
  params.type = data.type;
  params.algorithmId = 'task-' + dialogData.cameraForm.cameraId + '-' + data.type;
  return params;
}
function formatFormData(){
  let arr = [];
  let track = formatDetectionArea(dialogData.trackForm, 'track');
  let face = formatDetectionArea(dialogData.faceForm);
  let risk = formatDetectionArea(dialogData.riskForm, 'risk');
  let falling = formatDetectionArea(dialogData.fallingForm);
  let remnant = formatDetectionArea(dialogData.remnantForm, 'remnant');

  track.isAble && arr.push(track);
  face.isAble && arr.push(face);
  risk.isAble && arr.push(risk);
  falling.isAble && arr.push(falling);
  remnant.isAble && arr.push(remnant);
  
  dialogData.cameraForm['algorithmList'] = arr;
  let coordinateArr = [dialogData.cameraForm.coordinate.q1 || 0, dialogData.cameraForm.coordinate.q2 || 0, dialogData.cameraForm.coordinate.q3 || 0];
  dialogData.cameraForm['coordinate'] = coordinateArr + '';
}
</script>
<template>
  <div class="table_index">
    <SearchTable 
      :algorithmSelect="algorithmSelect" 
      :locationSelect="locationSelect" 
      :stateSelect="stateSelect" 
      :searchForm="searchForm" 
      @search="getTableData"
      @refresh="onRefresh"
      @add="changeDialog(true, 'Add')" />
    <div class="table_content">
      <mw-table
        :loading="tableLoading"
        :data="tableData"
        :pagination="pagination"
        @paginationChange="getTableData"
        @operate1="onEdit"
        @operate2="onDelete"
      ></mw-table>
    </div>
  </div>
  
  <mw-dialog
    :show="dialogData.show"
    width="600px"
    @submit="dialogSubmit"
    @close="changeDialog(false, null)"
  >
    <template #header="{ titleId, titleClass }">
      <div class="tabs_page" :id="titleId" :class="titleClass">
        <div 
          class="tabs_item" 
          :class="dialogData.tabsActive == item.value ? 'tabs_active' : ''" 
          v-for="item in dialogData.tabsList" 
          :key="item.value"
          @click="tabsClick(item.value)"
        >
          {{item.label}}
        </div>
      </div>
    </template>
    <el-form ref="dialogRefCamera" class="dialog_form form_dialog_box" :model="dialogData.cameraForm" label-width="210px" v-show="dialogData.tabsActive == 0">
      <el-form-item label="Camera ID" prop="cameraId" :rules="[{ required: true, message: 'Please input Camera ID', trigger: 'blur', }]">
        <el-input v-model="dialogData.cameraForm.cameraId" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Location">
        <el-select class="value_input" v-model="dialogData.cameraForm.location" placeholder="Please select" filterable clearable >
          <el-option v-for="item in locationSelect" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Resolution Ratio">
        <el-select class="value_input" v-model="dialogData.cameraForm.ratio" placeholder="Please select" filterable clearable >
          <el-option v-for="item in ratioSelect" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Pixel">
        <el-select class="value_input" v-model="dialogData.cameraForm.pixel" placeholder="Please select" filterable clearable >
          <el-option v-for="item in pixelSelect" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="IP">
        <el-input v-model="dialogData.cameraForm.ip" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="RTMP Stream Address">
        <el-input v-model="dialogData.cameraForm.rtmpUrl" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Coordinate">
        <div class="four_box">
          <el-input v-model="dialogData.cameraForm.coordinate.q1" type="number" class="value_input" style="width: 30%;" placeholder="X" clearable />
          <el-input v-model="dialogData.cameraForm.coordinate.q2" type="number" class="value_input" style="width: 30%" placeholder="Y" clearable />
          <el-input v-model="dialogData.cameraForm.coordinate.q3" type="number" class="value_input" style="width: 30%" placeholder="Z" clearable />
        </div> 
      </el-form-item>
    </el-form>
    
    <el-collapse class="form_dialog_box" v-model="collapseArr" v-show="dialogData.tabsActive == 1" @change="collapseChange">
      <el-collapse-item name="1">
        <template #title>
          <el-checkbox v-model="dialogData.trackForm.isAble"></el-checkbox>
          <el-icon class="collapse_icon" v-show="!collapseIncludes('1')"><Plus /></el-icon>
          <el-icon class="collapse_icon" v-show="collapseIncludes('1')"><Minus /></el-icon>
          People Track Identification
        </template>
        <el-form class="dialog_form collapse_form" :model="dialogData.trackForm" label-width="210px">
          <el-form-item label="Detection_Min_Size">
            <el-input v-model="dialogData.trackForm.detection_min_size" type="number" class="value_input" placeholder="Enter" clearable >
              <template #append>MB</template>
            </el-input>
          </el-form-item>
          <el-form-item label="Detection_Max_Size">
            <el-input v-model="dialogData.trackForm.detection_max_size" type="number" class="value_input" placeholder="Enter" clearable >
              <template #append>MB</template>
            </el-input>
          </el-form-item>
          <el-form-item label="Detection Period">
            <el-time-picker
              v-model="dialogData.trackForm.detectionPeriod"
              is-range
              format="HH:mm"
              clearable
              range-separator="To"
              start-placeholder="Start time"
              end-placeholder="End time"
            />
          </el-form-item>
          <el-form-item label="Detection Area">
            <div class="four_box">
              <el-input v-model="dialogData.trackForm.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.trackForm.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.trackForm.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
              <el-input v-model="dialogData.trackForm.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
            </div> 
          </el-form-item>
        </el-form>
      </el-collapse-item>
      <el-collapse-item name="2">
        <template #title>
          <el-checkbox v-model="dialogData.faceForm.isAble"></el-checkbox>
          <el-icon class="collapse_icon" v-show="!collapseIncludes('2')"><Plus /></el-icon>
          <el-icon class="collapse_icon" v-show="collapseIncludes('2')"><Minus /></el-icon>
          People Face Expression Identification
        </template>
        <el-form class="dialog_form collapse_form" :model="dialogData.faceForm" label-width="210px">
          <el-form-item label="Detection Period">
            <el-time-picker
              v-model="dialogData.faceForm.detectionPeriod"
              is-range
              format="HH:mm"
              clearable
              range-separator="To"
              start-placeholder="Start time"
              end-placeholder="End time"
            />
          </el-form-item>
          <el-form-item label="Detection Area">
            <div class="four_box">
              <el-input v-model="dialogData.faceForm.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.faceForm.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.faceForm.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
              <el-input v-model="dialogData.faceForm.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
            </div> 
          </el-form-item>
        </el-form>
      </el-collapse-item>
      <el-collapse-item name="3">
        <template #title>
          <el-checkbox v-model="dialogData.riskForm.isAble"></el-checkbox>
          <el-icon class="collapse_icon" v-show="!collapseIncludes('3')"><Plus /></el-icon>
          <el-icon class="collapse_icon" v-show="collapseIncludes('3')"><Minus /></el-icon>
          People Risk Scoring
        </template>
        <el-form class="dialog_form collapse_form" :model="dialogData.riskForm" label-width="210px">
          <el-form-item label="Gender">
            <el-select class="value_input" v-model="dialogData.riskForm.gender" placeholder="Please select" filterable clearable>
              <el-option v-for="item in globalVue.genderSelect" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="Age">
            <el-select class="value_input" v-model="dialogData.riskForm.age" placeholder="Please select" filterable clearable>
              <el-option v-for="item in globalVue.ageSelect" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="Hat">
            <el-select class="value_input" v-model="dialogData.riskForm.hat" placeholder="Please select" filterable clearable>
              <el-option v-for="item in globalVue.hatSelect" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="Wearing Glasses">
            <el-select class="value_input" v-model="dialogData.riskForm.wearingGlasses" placeholder="Please select" filterable clearable>
              <el-option v-for="item in globalVue.wearingGlassesSelect" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="Backpack">
            <el-select class="value_input" v-model="dialogData.riskForm.backpack" placeholder="Please select" filterable clearable>
              <el-option v-for="item in globalVue.backpackSelect" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="Handbag">
            <el-select class="value_input" v-model="dialogData.riskForm.handbag" placeholder="Please select" filterable clearable>
              <el-option v-for="item in globalVue.handbagSelect" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="Detection Period">
            <el-time-picker
              v-model="dialogData.riskForm.detectionPeriod"
              is-range
              format="HH:mm"
              clearable
              range-separator="To"
              start-placeholder="Start time"
              end-placeholder="End time"
            />
          </el-form-item>
          <el-form-item label="Detection Area">
            <div class="four_box">
              <el-input v-model="dialogData.riskForm.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.riskForm.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.riskForm.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
              <el-input v-model="dialogData.riskForm.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
            </div> 
          </el-form-item>
        </el-form>
      </el-collapse-item>
      <el-collapse-item name="4">
        <template #title>
          <el-checkbox v-model="dialogData.fallingForm.isAble"></el-checkbox>
          <el-icon class="collapse_icon" v-show="!collapseIncludes('4')"><Plus /></el-icon>
          <el-icon class="collapse_icon" v-show="collapseIncludes('4')"><Minus /></el-icon>
          Falling Detection
        </template>
        <el-form class="dialog_form collapse_form" :model="dialogData.fallingForm" label-width="210px">
          <el-form-item label="Detection Period">
            <el-time-picker
              v-model="dialogData.fallingForm.detectionPeriod"
              is-range
              format="HH:mm"
              clearable
              range-separator="To"
              start-placeholder="Start time"
              end-placeholder="End time"
            />
          </el-form-item>
          <el-form-item label="Detection Area">
            <div class="four_box">
              <el-input v-model="dialogData.fallingForm.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.fallingForm.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.fallingForm.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
              <el-input v-model="dialogData.fallingForm.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
            </div> 
          </el-form-item>
        </el-form>
      </el-collapse-item>
      <el-collapse-item name="5">
        <template #title>
          <el-checkbox v-model="dialogData.remnantForm.isAble"></el-checkbox>
          <el-icon class="collapse_icon" v-show="!collapseIncludes('5')"><Plus /></el-icon>
          <el-icon class="collapse_icon" v-show="collapseIncludes('5')"><Minus /></el-icon>
          Remnant Detection
        </template>
        <el-form class="dialog_form collapse_form" :model="dialogData.remnantForm" label-width="210px">
          <el-form-item label="Alert_Time_Threshold">
            <el-input v-model="dialogData.remnantForm.alert_time_threshold" class="value_input" placeholder="Enter" clearable />
          </el-form-item>
          <el-form-item label="Alert_Detection_Interval">
            <el-input v-model="dialogData.remnantForm.alert_detection_interval" class="value_input" placeholder="Enter" clearable />
          </el-form-item>
          <el-form-item label="Detection Period">
            <el-time-picker
              v-model="dialogData.remnantForm.detectionPeriod"
              is-range
              format="HH:mm"
              clearable
              range-separator="To"
              start-placeholder="Start time"
              end-placeholder="End time"
            />
          </el-form-item>
          <el-form-item label="Detection Area">
            <div class="four_box">
              <el-input v-model="dialogData.remnantForm.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.remnantForm.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
              <el-input v-model="dialogData.remnantForm.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
              <el-input v-model="dialogData.remnantForm.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
            </div> 
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>
  </mw-dialog>
</template>
<style lang="less" scoped>
.form_dialog_box{
  height: 400px;
  overflow: auto;
}
.four_box{
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
}
</style>